const objApp = window.external
const objCommon = objApp.CreateWizObject("WizKMControls.WizCommonUI")

//
const database = objApp.Database
//
const usertype = database.GetMeta("SERVER_INFO", "user_type")
const vip = (usertype == "vip")

const appGUID = objApp.GetPluginAppGUID(WizChromeBrowser)
objApp.PluginLocalizeHtmlDialog(WizChromeBrowser)

const app = new Vue({
  el: '#app',
  data: {
    loaded: false,
    message: 'Hello Vue!',
    url: 'http://localhost:8999/doc',
    username: '',
    password: '',
    token: '',
    blogTypeSelected: 'Hexo',
    blogTypeList: ['Hexo', 'Sina', 'JianShu', 'Others'],
    actionSelected: objApp.LoadPluginString(appGUID, 'Publish'),
    actionList: ['Publish', 'Post(replace)', 'Post(no replace)', 'Delete'].map((item) => {
      return objApp.LoadPluginString(appGUID, item)
    })
  },
  created () {
    this.loadConfig()
  },
  computed: {
    hint () {
      switch (this.blogTypeSelected) {
        case 'Hexo':
          return '标签将转化为Hexo中的标签，目录结构将转化为Hexo中的分类'
        default:
          return ''
      }
    },
    menuType () {
      return getQueryString("MenuType")
    },
    selectedDocuments () {
      let selectedDocuments = null
      let documents = []

      switch (this.menuType) {
        case 'NoteShare':
          selectedDocuments = objApp.CreateWizObject("WizKMCore.WizDocumentCollection")
          selectedDocuments.Add(objApp.Window.CurrentDocument)
          break
        case 'DocumentCtrlAdvanced':
          selectedDocuments = objApp.Window.DocumentsCtrl.SelectedDocuments
          break
        case 'CategoryCtrlDocumentsAdvanced':
          selectedDocuments = objApp.CreateWizObject("WizKMCore.WizDocumentCollection")
          selectedDocuments.Add(objApp.Window.CategoryCtrl.SelectedDocument)
          break
        default:
          break
      }

      for (let iDocument = 0; iDocument < selectedDocuments.Count; iDocument++) {
        let document = selectedDocuments.Item(iDocument)
        if (!document) {
          continue
        }
        documents.push(document)
      }

      return documents
    },
    documentTitleList () {
      if (null === this.selectedDocuments || this.selectedDocuments.Count === 0) {
        buttonOK.disabled = true
        alert(objApp.LoadPluginString(appGUID, "SelectOneDocument"))
        closeDialog(0)
      } else {
        return this.selectedDocuments.map((item) => {
          return item.Title
        }).join(';')
      }
    },
    postCooker () {
      let blogTypeIndex = this.blogTypeList.indexOf(this.blogTypeSelected)

      switch (blogTypeIndex) {
        case 0:
          return (obj) => {
            return obj
          }
        case 1:
          break
      }
    }
  },
  methods: {
    saveConfig () {
      localStorage.setItem('post-info:type', this.blogTypeSelected)
      localStorage.setItem('post-info:url', this.url)
      localStorage.setItem('post-info:action', this.actionSelected)
    },
    loadConfig () {
      let type = localStorage.getItem('post-info:type')
      let url = localStorage.getItem('post-info:url')
      let action = localStorage.getItem('post-info:action')
      if (type && type.length) {
        this.blogTypeSelected = type
      }
      if (url && url.length) {
        this.url = url
      }
      if (action && action.length) {
        this.actionSelected = action
      }
    },
    submit () {
      let optIndex = this.actionList.indexOf(this.actionSelected)
      let objProgress = objApp.CreateWizObject("WizKMControls.WizProgressWindow")
      let progress = 0
      objProgress.Title = objApp.LoadPluginString(appGUID, "Posting")
      objProgress.Max = this.selectedDocuments.length
      objProgress.Show()

      Promise.all(this.selectedDocuments.map((item) => {
        objProgress.Text = item.Title

        function end () {
          objProgress.Pos = ++progress
        }

        switch (optIndex) {
          case 0: {
            return this.postDocument(item, true, true).then(end)
          }
          case 1: {
            return this.postDocument(item, false, true).then(end)
          }
          case 2: {
            return this.postDocument(item, false, false).then(end)
          }
        }
      })).then(() => {
        this.saveConfig()
        objProgress.Hide()
        objProgress.Destroy()
        alert('post ok')
      }).catch(function (error) {
        objProgress.Hide()
        objProgress.Destroy()
        alert(error)
      })
    },
    postDocument (document, publish, replace) {
      let data = {
        type: 'wiz',
        replace,
        publish,
        title: this.getRealTitle(document.Title),
        tags: document.TagsText.length ? document.TagsText.split('\;').map(function (item) {
          return item.trim()
        }) : [],
        categories: document.Location.split('/').filter(function (item) {
          return item.length
        }).map(function (item) {
          return item.trim()
        }),
        content: WizIsMarkdown(document) ? document.GetText(0x0) : document.AbstractText
      }
      console.log(data)
      // console.log(document.Title, document.GetHtml(), document.AbstractText, document.Location)

      data = this.postCooker(data)
      //
      return axios.post(this.url, data).then(function (response) {
        if (response.data.code === 'invalid_param') {
          console.log(response.data.errors)
          alert('invalid_param')
          return Promise.reject(new Error(''))
        }
      })
    },
    deleteDocument (document) {
      let data = {
        type: 'wiz',
        title: this.getRealTitle(document.Title),
        tags: document.TagsText.replace(/\;/g, ","),
        content: document.GetHtml()
      }

      return axios.delete(this.url, data).then(function (response) {
        if (response.data.code === 'invalid_param') {
          console.log(response.data.errors)
          alert('invalid_param')
          return Promise.reject()
        }

        return Promise.resolve()
      }).catch(function (error) {
        console.log(error)
      })
    },
    cancel () {
      closeDialog(0)
    },
    encodePassword (password) {
      try {
        return objCommon.EncryptText("publishhtmlpublishhtml", password)
      } catch (e) {
        alert(e.message)
      }
      //
      return '';
    },
    decodePassword (password) {
      try {
        let decode = objCommon.DecryptText(appGUID, password);
        if (!decode) {
          decode = password
        }
        //
        return decode
      } catch (e) {
        alert(e.message)
      }
      //
      return '';
    },
    getRealTitle (title) {
      if (title.length >= '.md'.length && title.substr(title.length - '.md'.length, '.md'.length) == '.md')
      {
        title = title.substr(0, title.length - '.md'.length);
      }
      if (title.length >= '.mj'.length && title.substr(title.length - '.mj'.length, '.mj'.length) == '.mj')
      {
        title = title.substr(0, title.length - '.mj'.length);
      }
      return title
    }
  }
})

function WizIsMarkdown(wizDoc) {
  try {
    var title = wizDoc.Title;

    if (-1 != title.indexOf(".md ")) {
      return true;
    }
    if (title.lastIndexOf(".md") == -1) {
      return false;
    }
    if (title.lastIndexOf(".md") == title.length - 3) {
      return true;
    }
    return false;
  }
  catch (err) {
    return false;
  }
}

function getQueryString (name) {
  if (location.href.indexOf("?") == -1 || location.href.indexOf(name + '=') == -1) {
    return ''
  }
  var queryString = location.href.substring(location.href.indexOf("?") + 1)

  var parameters = queryString.split("&")

  var pos, paraName, paraValue
  for (var i = 0; i < parameters.length; i++) {
    pos = parameters[i].indexOf('=')
    if (pos == -1) { continue }

    paraName = parameters[i].substring(0, pos)
    paraValue = parameters[i].substring(pos + 1)

    if (paraName == name) {
      return unescape(paraValue.replace(/\+/g, " "))
    }
  }
  return ''
}

function closeDialog (ret) {
  objApp.Window.CloseHtmlDialog(WizChromeBrowser, ret)
}